package com.lagou.common.rpc;

import com.lagou.common.domain.ServiceData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RpcRoute {
    public ConcurrentHashMap<String, ServiceData> handlerMap;
    public void init(ConfigurableApplicationContext context) throws InterruptedException {
        this.handlerMap = new ConcurrentHashMap<>();
        ServerStub serverStub = new ServerStub("127.0.0.1", 8990);
        serverStub.start();
        Map<String, Object> beansWithAnnotation = context.getBeansWithAnnotation(Service.class);
        if(!beansWithAnnotation.isEmpty()){
            for (Object bean: beansWithAnnotation.values()) {
                Class<?> serviceImp = bean.getClass();
                Method[] methods = serviceImp.getMethods();
                for(Method method: methods){
                    Value annotation1 = method.getAnnotation(Value.class);
                    if(annotation1!=null){
                        String methodName = annotation1.value();
                        ServiceData serviceData = new ServiceData();
                        serviceData.setaClass(serviceImp);
                        serviceData.setMethod(method);
                        handlerMap.put(methodName, serviceData);
                    }
                }
            }
        }
    }
    private static RpcRoute rpcRoute;
    private RpcRoute(){ }

    public static RpcRoute getInstance(){
        if(rpcRoute==null){
            synchronized (RpcRoute.class){
                rpcRoute = new RpcRoute();
            }
        }
        return  rpcRoute;
    }
}
